#AWS credentials should not be placed in this file, but rather initialized as environment variables or in configuration files.
import time
import boto
from boto.ec2.connection import EC2Connection
from boto.ec2.address    import Address
from boto.ec2.instance   import Reservation
from boto.ec2.instance   import InstanceState

class Client_InstanceManager():

	regionID    = str()
	connection  = None
	
	
	def __init__(self):
		self.regionID = boto.ec2.get_region('eu-west-1')
		self.connection = EC2Connection(region=self.regionID)
	
	
	def start(self, honeypot_count):

		#Reserve Elastic IPs for both the monitor and the honeypots and retain all Address objects
		elasticIP = [self.connection.allocate_address() for i in range(0, honeypot_count+1)]

		
		#Start instances and retain all reservation objects
		reservation.append(self.runEC2Instance('ami-a6e6edd2', 'LIA-HAAS_pub', 'LIA_HaaS_Monitor')) 
		reservation.extend([self.runEC2Instance('ami-a6e6edd2', 'LIA-HAAS_pub', 'LIA_HaaS_Monitor') for i in range(0, honeypot_count)])


		#Distribute reserved elastic IPs to all instances
		for index in range(0, len(reservation)):
			#Loop until instance is in a running state in order to change IP assignment
			while str(reservation[index].instances[0].state) != "running":
				time.sleep(5)
				reservation[index].instances[0].update()
			#Change the elastic IPs of the instances
			self.connection.associate_address(
								instance_id = str(reservation[index].instances[0].id),
								public_ip = str(elasticIP[index])[8:])

		#Write details to file in the form:
		#
		# monitorIP: honeypotIP_1, honeypotIP_2, ...
		#
		fileHandle = fopen("/opt/client_layout", "a")
		for i in range(0, len(elasticIP)):
			if i == 0:
				fileHandle.write(elasticIP[i]+": ")
			elif i != len(elasticIP)-1:
				fileHandle.write(elasticIP[i]+", ")
			else:
				fileHandle.write(elasticIP[i]+"\n")
				
		
	#def stop(self, monitorIP):
			



	def runEC2Instance(self, amiImageID, sec_group, keyName):
		return self.connection.run_instances(
							str(amiImageID),
							key_name=str(keyName),
							instance_type='t1.micro',
							security_groups=[str(sec_group)])
		

	#Testing only
	def getAllreservations(self):
		return self.connection.get_all_addresses()
		
	#Testing only
	def releaseReservations(self):
		reservation = self.getAllreservations()
		for i in range(0, len(reservation)):
			reservation[i].delete()


	#Testing only
	def test(self):


		elasticIP = [self.connection.allocate_address() for i in range(0, 2)]
		print str(elasticIP[0])[8:]
		
		#print reservation[0].id
		
		#print reservation[0]
		#print reservation[0].id
						
		
		#elasticIP_monitor = self.connection.allocate_address()
		#print monitor_publicIP
		#elasticIP_honeypot = [{i:str(self.connection.allocate_address())} for i in range(0, 2)]
		#print honeypot_publicIP
		
		
		
		#self.releaseReservations()
		
		

		#honeypot_publicIP = [{i:str(self.connection.allocate_address())} for i in numHPs]
		#print monitor_publicIP
		#print honeypot_publicIP


if __name__ == '__main__':
	
	bla = Client_InstanceManager()
	#bla.releaseReservations()
	bla.start(1)

	
